<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_EditGroup extends Paylog_Abstract_Controller
{
	protected $groupHand = null;
	protected $groupId   = null;
	protected $groupObj  = null;

	protected $input  = array();
	protected $errors = array();

	public function __construct()
	{
		parent::__construct();

		$this->groupHand = new Paylog_Object_GroupHandler;
		$this->groupId   = Paylog::get('id', 0);
		$this->groupObj  = $this->groupHand->load($this->groupId);

		$name   = $this->groupObj->getVar('name');
		$weight = $this->groupObj->getVar('weight');

		$name   = Paylog::post('name', $name);
		$weight = Paylog::post('weight', $weight);

		$this->input = array(
			'name'   => $name,
			'weight' => $weight,
		);
	}

	public function main()
	{
		$this->_validateAccess();

		if ( Paylog::post('submit') )
		{
			try
			{
				$this->_save();
			}
			catch ( Exception $e )
			{
				$this->_default();
			}
		}
		else
		{
			$this->_default();
		}
	}

	protected function _save()
	{
		$token = Paylog::post('token');

		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->_addError("Ticket Error");
			$this->_riseError();
		}

		$this->groupObj->setVar('name', $this->input['name']);
		$this->groupObj->setVar('weight', $this->input['weight']);

		if ( $this->groupHand->save($this->groupObj) )
		{
			Paylog::redirect("Group successly updated.", Paylog::$dirname, 'edit_group');
		}
		else
		{
			$this->_addError("Group updating failed.");
			$this->_riseError();
		}
	}

	protected function _default()
	{
		$this->output['input']  = $this->input;
		$this->output['token']  = Paylog_Class_Ticket::issue();
		$this->output['errors'] = $this->errors;

		$this->_view();
	}

	protected function _validateAccess()
	{
		if ( $this->groupId < 0 )
		{
			Paylog::redirect("Group ID is invalid.");
		}

		if ( $this->groupId > 0 and !$this->groupHand->isIdExists($this->groupId) )
		{
			Paylog::redirect("Such a group does not exist.");
		}
	}

	protected function _addError($msg)
	{
		$this->errors[] = Paylog::msg($msg);
	}

	protected function _riseError()
	{
		throw new Exception();
	}
}

?>
